package com.example.juc.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author jl
 * @since 2021/10/11 19:51
 * SimpleDateFormat线程安全问题示例
 */
public class SimpleDateFormatDemo {
    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public static Date parse(String StringDateFormat) throws ParseException {
        return sdf.parse(StringDateFormat);
    }

    public static final ThreadLocal<SimpleDateFormat> thread = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd"));

    public static Date parseByThreadLocal(String stringDateFormat) throws ParseException {
        return thread.get().parse(stringDateFormat);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 30; i++) {
            new Thread(() -> {
                try {
//                    System.out.println(SimpleDateFormatDemo.parse("2021-11-11 11:11:11"));
                    System.out.println(SimpleDateFormatDemo.parseByThreadLocal("2021-11-11 11:11:11"));
                } catch (ParseException e) {
                    e.printStackTrace();
                } finally {
                    thread.remove();
                }
            }).start();
        }
    }
}
